package com.ygl.sba;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

/**
 * @Author yanggld
 * @Date 2020/1/15-9:22
 * @Description
 */
@Slf4j
public class DingtalkNotifier {
	public void sendMsg(NotificationType type, ServiceInstance serviceInstance) throws Exception {
		DingTalkClient client = new DefaultDingTalkClient(getUrl());
		OapiRobotSendRequest request = new OapiRobotSendRequest();
		request.setMsgtype("text");
		OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);
		if (type.equals(NotificationType.DOWN)) {
			String content = String.format("[%s][服务下线DOWN]%n%s", time, serviceInstance.getMetadata().get("nacos.instanceId"));
			text.setContent(content);
		} else if (type.equals(NotificationType.UP)) {
			String content = String.format("[%s][服务上线UP]%n%s", time, serviceInstance.getMetadata().get("nacos.instanceId"));
			text.setContent(content);
		}

		request.setText(text);
		OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
		at.setIsAtAll("true");
		request.setAt(at);
		OapiRobotSendResponse response = client.execute(request);
		if (!response.isSuccess()) {
			log.error("发送失败："+response.getErrmsg());
		} else{
			String body = response.getBody();
			log.info("发送成功:"+body);
		}
	}

	private String getUrl() throws Exception {
		Long timestamp = System.currentTimeMillis();
		String url = "https://oapi.dingtalk.com/robot/send?access_token=11ece487e69fbb80e1effd22eb20d46432a2fecdad2ee0c4a8e1b39c992cde82&" +
				"timestamp="+timestamp+"&sign="+getSign();
		return url;
	}

	private String secret = "SEC8805fa9397d2ece3f7d8eb15c9fec66a215962083d396c71cdee012c7105bbcc";

	private String getSign() throws Exception {
		Long timestamp = System.currentTimeMillis();
		String stringToSign = timestamp + "\n" + secret;
		Mac mac = Mac.getInstance("HmacSHA256");
		mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
		byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
		Base64.Encoder encoder = Base64.getEncoder();
		String sign = encoder.encodeToString(signData);
		return URLEncoder.encode(sign,"UTF-8");
	}
}
